package com.yunmang.activity.ordermanager;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.yunmang.R;
import com.yunmang.activity.BaseActivity;
import com.yunmang.activity.SearchEndActivity;
import com.yunmang.app.AppConstant;
import com.yunmang.entity.GoodsBean;
import com.yunmang.entity.MemberBean;
import com.yunmang.entity.NameBean;
import com.yunmang.entity.ParameterEntity.EditBillBean;
import com.yunmang.entity.ParameterEntity.OrderLookBean;
import com.yunmang.entity.event.EndEvent;
import com.yunmang.http.HttpUtils;
import com.yunmang.utils.CommonUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;

/**
 * Created by Administrator on 2017/5/25.
 */
public class UpdateOrderInfoActivity extends BaseActivity implements OnItemClickListener {
    @InjectView(R.id.toolbar)
    Toolbar mToolbar;
    @InjectView(R.id.et_date)
    TextView etDate;
    @InjectView(R.id.tv_delivery_station)
    TextView tvDeliveryStation;
    @InjectView(R.id.et_hdbh)
    EditText etHdbh;
    @InjectView(R.id.cb_hdbh)
    CheckBox cbHdbh;
    @InjectView(R.id.et_zd_station)
    TextView etZdStation;
    @InjectView(R.id.et_zz_station)
    EditText etZzStation;
    @InjectView(R.id.iv_card)
    TextView ivCard;
    @InjectView(R.id.et_card_number)
    EditText etCardNumber;
    @InjectView(R.id.et_fh_number)
    EditText etFhNumber;
    @InjectView(R.id.et_sh_number)
    EditText etShNumber;
    @InjectView(R.id.et_sh_name)
    EditText etShName;
    @InjectView(R.id.tv_shd_address)
    TextView tvShdAddress;
    @InjectView(R.id.et_sh_address)
    EditText etShAddress;
    @InjectView(R.id.et_cargo_name)
    EditText etCargoName;
    @InjectView(R.id.spinner_pack)
    TextView spinnerPack;
    @InjectView(R.id.cargo_number)
    EditText cargoNumber;
    @InjectView(R.id.et_cargo_quality)
    EditText etCargoQuality;
    @InjectView(R.id.et_cargo_bulk)
    EditText etCargoBulk;
    @InjectView(R.id.et_fh_name)
    EditText etFhName;
    @InjectView(R.id.iv_balance)
    TextView ivBalance;
    @InjectView(R.id.spinner_count_style)
    TextView spinnerCountStyle;
    @InjectView(R.id.et_zz_money)
    EditText etZzMoney;
    @InjectView(R.id.et_cargo_freight)
    EditText etCargoFreight;
    @InjectView(R.id.et_delivery_charge)
    EditText etDeliveryCharge;
    @InjectView(R.id.et_collect_money)
    EditText etCollectMoney;
    @InjectView(R.id.et_insure_fare)
    EditText etInsureFare;
    @InjectView(R.id.et_rebates)
    EditText etRebates;
    @InjectView(R.id.rb_ziti)
    RadioButton rbZiti;
    @InjectView(R.id.rb_sh)
    RadioButton rbSh;
    @InjectView(R.id.rg_delivery_style)
    RadioGroup rgDeliveryStyle;
    @InjectView(R.id.rg_is_receipt)
    RadioGroup rgIsReceipt;
    @InjectView(R.id.et_note_number)
    EditText etNoteNumber;
    @InjectView(R.id.et_remark)
    EditText etRemark;
    @InjectView(R.id.cb_hkyf)
    CheckBox cbHkyf;
    @InjectView(R.id.cb_dyyd)
    CheckBox cbDyyd;
    @InjectView(R.id.cb_dybq)
    CheckBox cbDybq;
    @InjectView(R.id.cb_dnbq)
    CheckBox cbDnbq;
    @InjectView(R.id.cb_remind_shr)
    CheckBox cbRemindShr;
    @InjectView(R.id.cb_fkpz)
    CheckBox cbFkpz;
    @InjectView(R.id.btn_save)
    Button btnSave;
    @InjectView(R.id.ll_biaoqian)
    LinearLayout llBiaoqian;
    @InjectView(R.id.ll_bottom)
    LinearLayout ll_bottom;
    @InjectView(R.id.tv_reason)
    TextView tvReason;
    private OrderLookBean.ModelBean.ItemsBean itemsBean;//存放的缓存数据
    private Subscriber<NameBean> subscriber;
    private Subscriber mSubScriber;
    private int endId,memberid,balance;
    private String method;
    private AlertView mConfirmAlert;
    @Override
    public int getLayoutId() {
        return R.layout.activity_update_order;
    }

    @Override
    public void initView() {
        ButterKnife.inject(this);
        EventBus.getDefault().register(this);
        initToolbar();
        llBiaoqian.setVisibility(View.GONE);
        ll_bottom.setVisibility(View.GONE);
        tvReason.setText("修改原因");
        etCardNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {

                } else {
                    String card = etCardNumber.getText().toString().trim();
                    if (!TextUtils.isEmpty(card)) {
                        getMemberInfo(card);
                    }
                }
            }
        });
        etFhNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {

                } else {
                    String shipper = etFhNumber.getText().toString().trim();
                    if (!TextUtils.isEmpty(shipper)) {
                        getShipperName(shipper);

                    }
                }
            }
        });
        etShNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {

                } else {
                    String consignee = etShNumber.getText().toString().trim();
                    if (!TextUtils.isEmpty(consignee)) {
                        getConsigneeName(consignee);
                    }
                }
            }
        });
        cargoNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                etNoteNumber.setText(charSequence.toString());
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void initToolbar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("运单修改");
        mToolbar.setNavigationIcon(R.mipmap.ic_back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    public void initData() {
        itemsBean = AppConstant.itemsBean;
        endId = itemsBean.getEndOrgId();
        method=itemsBean.getTakeMethod();
        if(method.equals("自提")){
            rbZiti.setChecked(true);
        }else{
            rbSh.setChecked(true);
        }
        //可修改的
        etZdStation.setText(itemsBean.getEndOrgName());
        etFhNumber.setText(itemsBean.getShipperPhone());
        etFhName.setText(itemsBean.getShipper());
        etShName.setText(itemsBean.getConsignee());
        etShNumber.setText(itemsBean.getConsigneePhone());
        etCargoFreight.setText(itemsBean.getTransportCost() + "");
        etCollectMoney.setText(itemsBean.getGoodsCost() + "");
        etDeliveryCharge.setText(itemsBean.getDeliveryCost() + "");
        //标示颜色
        etZdStation.setTextColor(getResources().getColor(R.color.colorPrimary));
        etFhNumber.setTextColor(getResources().getColor(R.color.colorPrimary));
        etFhName.setTextColor(getResources().getColor(R.color.colorPrimary));
        etShName.setTextColor(getResources().getColor(R.color.colorPrimary));
        etShNumber.setTextColor(getResources().getColor(R.color.colorPrimary));
        etCargoFreight.setTextColor(getResources().getColor(R.color.colorPrimary));
        etCollectMoney.setTextColor(getResources().getColor(R.color.colorPrimary));
        etDeliveryCharge.setTextColor(getResources().getColor(R.color.colorPrimary));
        //不可修改
        etDate.setText(itemsBean.getBillDate());
        etHdbh.setText(itemsBean.getHdbh());
        tvDeliveryStation.setText(itemsBean.getStartOrgName());
        etCargoName.setText(itemsBean.getGoodsName());
        cargoNumber.setText(itemsBean.getNumbers());
        etZzMoney.setText(itemsBean.getTransferCost() + "");
        spinnerCountStyle.setText(itemsBean.getBalanceMethod());
        spinnerPack.setText(itemsBean.getPack());
        etCargoQuality.setText(itemsBean.getWeight());
        etCargoBulk.setText(itemsBean.getCubage());
        etCardNumber.setText(itemsBean.getMemberCode());
        etZzStation.setText(itemsBean.getTransferAddress());
        etShAddress.setText(itemsBean.getConsigneeAddress());
        spinnerPack.setText(itemsBean.getPack());
        etDate.setTextColor(getResources().getColor(R.color.red));
        etHdbh.setTextColor(getResources().getColor(R.color.red));
        etCargoName.setTextColor(getResources().getColor(R.color.red));
        etCardNumber.setTextColor(getResources().getColor(R.color.red));
        cargoNumber.setTextColor(getResources().getColor(R.color.red));
        tvDeliveryStation.setTextColor(getResources().getColor(R.color.red));
        etZzStation.setTextColor(getResources().getColor(R.color.red));
        etZzMoney.setTextColor(getResources().getColor(R.color.red));
        spinnerCountStyle.setTextColor(getResources().getColor(R.color.red));
        spinnerPack.setTextColor(getResources().getColor(R.color.red));
        etCargoQuality.setTextColor(getResources().getColor(R.color.red));
        etCargoBulk.setTextColor(getResources().getColor(R.color.red));
        etCardNumber.setTextColor(getResources().getColor(R.color.red));
        etShAddress.setTextColor(getResources().getColor(R.color.red));
        spinnerPack.setTextColor(getResources().getColor(R.color.red));

    }

    @OnClick({R.id.et_zd_station, R.id.btn_save})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.et_zd_station:
                startActivity(new Intent(this, SearchEndActivity.class));
                break;
            case R.id.btn_save:
                if(itemsBean.isCanEdit()){
                    if (etCardNumber.hasFocus()) {//如果有焦点
                        String cd = etCardNumber.getText().toString().trim();
                        if (!TextUtils.isEmpty(cd)) {
                            getMemberInfo(cd);
                        }
                    }
                    submitData(constract());
                }else{
                    setmConfirmAlert();
                }
                break;
        }
    }

    private String constract() {
        Gson gson = new Gson();
        EditBillBean bean = new EditBillBean();
        bean.setId(itemsBean.getId());
        bean.setHdbh(itemsBean.getHdbh());
        bean.setEndDepartmentId(endId);
        bean.setShipper(CommonUtils.getTextViewValue(etFhName));
        bean.setShipperPhone(CommonUtils.getTextViewValue(etFhNumber));
        bean.setConsignee(CommonUtils.getTextViewValue(etShName));
        bean.setConsigneePhone(CommonUtils.getTextViewValue(etShNumber));
        bean.setMemberNo(CommonUtils.getTextViewValue(etCardNumber));
        bean.setTransportCost(Double.valueOf(CommonUtils.getTextViewValue(etCargoFreight)));
        bean.setGoodsCost(Double.valueOf(CommonUtils.getTextViewValue(etCollectMoney)));
        String bm=itemsBean.getBalanceMethod();
        bean.setBalanceMethod(CommonUtils.getBalanceMethod(bm));
        bean.setDeliveryCost(Double.valueOf(CommonUtils.getTextViewValue(etDeliveryCharge)));
        bean.setUserId(Integer.parseInt(AppConstant.userid));
        if(rbZiti.isChecked()){
            method="自提";
        }else{
            method="送货";
        }
        bean.setTakeMethod(method);
        bean.setApplyReason(CommonUtils.getTextViewValue(etRemark));
        List<GoodsBean> list=new ArrayList<>();
        GoodsBean goodsBean = new GoodsBean();
        goodsBean.setGoodsName(CommonUtils.getTextViewValue(etCargoName));
        goodsBean.setPack(CommonUtils.getTextViewValue(spinnerPack));
        goodsBean.setNumbers(CommonUtils.getTextViewValue(cargoNumber));
        goodsBean.setCubage(CommonUtils.getTextViewValue(etCargoBulk));
        goodsBean.setWeight(CommonUtils.getTextViewValue(etCargoQuality));
        list.add(goodsBean);
        return gson.toJson(bean);
    }

    /**
     * 获取会员卡信息
     * @param code 10014
     */
    private void getMemberInfo(String code) {
        showWaitingDialog("正在获取……");
        mSubScriber = new Subscriber<MemberBean>() {
            @Override
            public void onCompleted() {
                hideWaitingDialog();
            }
            @Override
            public void onError(Throwable e) {
                hideWaitingDialog();
                clearEditInfo(etCardNumber);
                showToast("onError" + e.toString());
            }
            @Override
            public void onNext(MemberBean memberBean) {
                hideWaitingDialog();
                if (memberBean.getCode() == 200) {
                    if (memberBean.getModel() != null) {
                        etFhNumber.setText(memberBean.getModel().getTelephone());
                        etFhName.setText(memberBean.getModel().getName());
                        memberid = memberBean.getModel().getId();
                    } else {
                        clearEditInfo(etCardNumber);
                        showToast("暂无该卡号");
                    }
                } else {
                    clearEditInfo(etCardNumber);
                    showToast(memberBean.getMessage().toString());
                }
            }
        };
        HttpUtils.getInstance().getMemberInfo(mSubScriber, code);
    }


    /**
     * 获取发货人姓名
     *
     * @param consigneeName
     */
    private void getConsigneeName(String consigneeName) {
        mSubScriber = new Subscriber<NameBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                showToast("onError" + e.toString());
            }

            @Override
            public void onNext(NameBean nameBean) {
                if (nameBean.getCode() == 200) {
                    if (nameBean.getModel() != null) {
                        etShName.setText(nameBean.getModel());
                    } else {
                    }
                } else {
                }
            }

        };
        HttpUtils.getInstance().getConsignee(mSubScriber, consigneeName);
    }

    private void getShipperName(String shipperNumber) {
        mSubScriber = new Subscriber<NameBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                showToast("onError" + e.toString());
            }

            @Override
            public void onNext(NameBean nameBean) {
                if (nameBean.getCode() == 200) {
                    if (!TextUtils.isEmpty(nameBean.getModel())) {
                        etFhName.setText(nameBean.getModel());
                    } else {
                    }
                } else {
                }
            }
        };
        HttpUtils.getInstance().getshipper(mSubScriber, shipperNumber);
    }

    private void submitData(String inJson) {
        showWaitingDialog("数据提交中……");
        subscriber = new Subscriber<NameBean>() {
            @Override
            public void onCompleted() {
                hideWaitingDialog();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                showAlertDialog("修改异常");
            }

            @Override
            public void onNext(NameBean nameBean) {
                if(nameBean.getCode()==200){
                    EventBus.getDefault().post("refresh");
                    String model = nameBean.getModel();
                    if(model.equals("true")){

                        showAlertDialog("修改成功");
                    }else{
                        showAlertDialog("提交成功，需要进行审批");
                    }
                }else{
                    showAlertDialog("修改失败");
                }
            }
        };
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), inJson);
        HttpUtils.getInstance().editBill(subscriber, body);
    }

    public void onEventMainThread(EndEvent event) {
        endId = event.getId();
        etZdStation.setText(event.getName());
    }

    private void setmConfirmAlert() {
        mConfirmAlert = new AlertView("提示", "该票据不能修改", "取消", new String[]{"确定"}, null, this, AlertView.Style.Alert, this);
        mConfirmAlert.setCancelable(true).show();
    }

    /**
     * 弹出对话框
     * @param string
     * */
    private void showAlertDialog(String string) {
        new AlertView("提示",string, null,new String[]{"确定"}, null,this,AlertView.Style.Alert,this).show();
    }


    @Override
    public void onItemClick(Object o, int position) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
